require "Common/functions"

EffectManager = {};
local this = EffectManager;

local effectPool = {};
local effectPoolRoot = nil;

function EffectManager.init()
    effectPool = {};
end

function EffectManager.destroy()
    this.clearAllEff();
end

function EffectManager.createEffectPool(parent,obj,capacity)
	effectPoolRoot = parent;
    local objname = obj.name;
    if effectPool[objname] == nil then
        effectPool[objname] = {};

        for i=1,capacity do
			local effgo = newObject(obj);
			if effectPoolRoot ~= nil then
				effgo.transform:SetParent(effectPoolRoot);
			end
            effgo:SetActive(false);
			table.insert(effectPool[objname], effgo);
        end
    end

end

function EffectManager.getEffect(key)
	local eList = effectPool[key]
	if eList == nil then
		return nil
	end
	local go = table.remove(eList, 1)
	if go == nil then
		return nil;
	end
	go.gameObject:SetActive(true)
	return go
end

function EffectManager.releaseEffect(go, key_name)
	--if go == nil or tostring(go) == "null" then return end
	if HelperFunc.IsNull(go) then
		return
	end
	
	if effectPoolRoot ~= nil then
		go.transform:SetParent(effectPoolRoot);
	end
	go:SetActive(false)
	
	local key = nil 
	if key_name == nil then
		local goName = go.name
		local first = string.find(goName,"Clone")
		
		if first ~= nil then
			key = string.sub(goName,1,first-2)
		else
			key = goName
		end 
	else
		key = key_name
	end
	local eList = effectPool[key]
	if eList == nil then
		eList = {}
	end
	table.insert(eList, go);
	effectPool[key] = eList;
end

function EffectManager.clearAllEff()
    for k,v in pairs(effectPool) do
		for _, eff in pairs(v) do
			destroy(eff);
		end
    end
    effectPool = {};
end

